package com.springredis.controller;

import com.springredis.pojo.Book;
import com.springredis.service.BookService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.*;

@Controller
public class BookController {
	@Resource
	BookService bookService;
	@ResponseBody
	@GetMapping("/setValue")
	public String setValue(){
		bookService.setValue("redis","Spring Data Redis");
		return "保存键值对成功";
	}
	@ResponseBody
	@GetMapping("/getValue")
	public String getValue(){
		return bookService.getValue("redis");
	}

	@ResponseBody
	@GetMapping("/saveBook")
	public String saveBook(){
		Book book=new Book(1,"C语言程序设计",50.0,"计算机",100,"101.jpg","","zhangsan",50);
		bookService.saveBook(book);
		return "保存成功";
	}
	@GetMapping("/findBook")
	public String findBookById(Model model){
		model.addAttribute("book",bookService.findBookById(1));
		return "book";
	}

	@ResponseBody
	@GetMapping("/saveBooks")
	public String saveBooks(){
		Book book1=new Book(1,"C语言程序设计",50.0,"计算机",100,"101.jpg","","zhangsan",50);
		Book book2=new Book(2,"Java语言程序设计",60.0,"计算机",100,"102.jpg","","zhangsan",50);
		Book book3=new Book(3,"Python语言程序设计",70.0,"计算机",100,"103.jpg","","zhangsan",50);
		List<Book>bookList=new ArrayList<>();
		bookList.add(book1);
		bookList.add(book2);
		bookList.add(book3);
		bookService.saveBooks("101",bookList);
		return "保存多本书成功";
	}
	@GetMapping("/findBooks")
	public String findBooks(Model model){
		model.addAttribute("books",bookService.findBooks("101"));
		return "books";
	}
	@GetMapping("/findBookById/{id}")
	public String findBookById(@PathVariable Integer id, Model model){
		List<Book> books = bookService.findBooks("101");
		Book book=new Book();
		if (books!=null&& !books.isEmpty()){
			book=books.get(id-1);
		}
		model.addAttribute("book",book);
		return "book";
	}
	@GetMapping("/deleteBook/{id}")
	public String deleteBook(@PathVariable Integer id,Model model){
		List<Book> books = bookService.findBooks("101");
		if (books!=null&& !books.isEmpty()){
			books.remove(id-1);
		}
		bookService.saveBooks("101",books);
		model.addAttribute("books",books);
		return "books";
	}
}
